package com.sskj.level.ui.fragment;


import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.Entrust;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.TradeListFragmentPresenter;
import com.sskj.level.ui.activity.TradeListActivity;
import com.sskj.level.util.TipLevelUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.MainTabChange;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.bigkoo.pickerview.view.WheelTime.dateFormat;

@Route(path = RConfig.LEVEL_FRAGMENT_TRADE_LIST)//交易记录
public class TradeListFragment extends BaseFragment<TradeListFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.includeEmpty)
    View includeEmpty;

    private SlimAdapter<Entrust> slimAdapter;
    @Autowired
    String fragmentType;
    private int curPos;
    @Inject
    UserViewModel userViewModel;
    private Disposable subscribe;
    private MaterialDialog setTip;
    private UserData userData;
    private MaterialDialog cancelTip;

    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_trade_list;
    }

    @Override
    public TradeListFragmentPresenter getPresenter() {
        return new TradeListFragmentPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);

        ARouter.getInstance().inject(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        SlimAdapter level_item_trade_history = SlimAdapter.create().register(R.layout.level_item_trade_history, new SlimInjector<Entrust>() {
            @Override
            public void onInject(Entrust item, IViewInjector injector, List payloads) {
                injector
                        .text(R.id.item_entrust_type, item.getType() == 1 ? App.INSTANCE.getString(R.string.levelCurrentHolderFragment12) : App.INSTANCE.getString(R.string.levelCurrentHolderFragment13))
                        .textColor(R.id.item_entrust_type, item.getType() == 1 ? getResources().getColor(R.color.levelGreenText) : getResources().getColor(R.color.levelRedText))
                        .text(R.id.item_entrust_name, item.getL_code().toUpperCase() + "/" + item.getR_code().toUpperCase())
                        .text(R.id.item_lookOrder0008, String.format(App.INSTANCE.getString(R.string.level_lookOrder0008), item.getR_code().toUpperCase()))
                        .text(R.id.item_lookOrder0009, String.format(App.INSTANCE.getString(R.string.level_lookOrder0009), item.getR_code().toUpperCase()))
                        .text(R.id.item_lookOrder00010, String.format(App.INSTANCE.getString(R.string.level_lookOrder00010), item.getR_code().toUpperCase()))
                        .text(R.id.item_lookOrder00011, String.format(App.INSTANCE.getString(R.string.level_lookOrder00011), item.getR_code().toUpperCase()))
                        .text(R.id.item_lookOrder00012, String.format(App.INSTANCE.getString(R.string.level_lookOrder00012), item.getL_code().toUpperCase()))
                        .text(R.id.item_entrust_time, dateFormat.format(Long.parseLong(item.getAdd_time()) * 1000))
                        .text(R.id.item_entrust_price, item.getWtprice())
                        .text(R.id.tv_weiTuoJinE, item.getWtprice1())
                        .text(R.id.tv_ChengJiaoZongE, item.getTotalprice())
                        .text(R.id.tv_ChengJiaoJunJia, item.getCjprice())
                        .text(R.id.item_entrust_real_num, item.getCjnum());

                TextView cancel = (TextView) injector.findViewById(R.id.item_entrust_cancel);
                cancel.setTextColor(getResources().getColor(R.color.blue_5d));

                cancel.setVisibility(View.VISIBLE);
                if (item.getCode() == 0) {
                    //0 委托中
                    cancel.setText(App.INSTANCE.getString(R.string.strEntrustActivity208));
                } else if (item.getCode() == 1) {
                    //1 交易中
                    cancel.setText(App.INSTANCE.getString(R.string.strEntrustActivity209));
                } else if (item.getCode() == 2) {
                    //2已成交
                    cancel.setText(App.INSTANCE.getString(R.string.strEntrustActivity206));
                } else if (item.getCode() == -1) {
                    // -1 已撤销
                    cancel.setText(App.INSTANCE.getString(R.string.strEntrustActivity207));
                } else {
                    cancel.setVisibility(View.GONE);
                }
                if (item.getCode() == 0 || item.getCode() == 1) {
                    cancel.setClickable(true);
                    cancel.setOnClickListener(v -> mPresenter.cancelOrder(item.getOrders_id()));
                } else {
                    cancel.setClickable(false);
                }
            }
        });

        SlimAdapter item_recycler_entrust = SlimAdapter.create().register(R.layout.item_recycler_entrust, new SlimInjector<Entrust>() {
            @Override
            public void onInject(Entrust item, IViewInjector injector, List payloads) {
                injector
                        .text(R.id.item_entrust_name, item.getPname())
                        .text(R.id.item_entrust_type, item.getType() == 1 ? App.INSTANCE.getString(R.string.levelCurrentHolderFragment12) : App.INSTANCE.getString(R.string.levelCurrentHolderFragment13))
                        .textColor(R.id.item_entrust_type, item.getType() == 1 ? getResources().getColor(R.color.levelGreenText) : getResources().getColor(R.color.levelRedText))
                        .text(R.id.item_entrust_time, dateFormat.format(Long.parseLong(item.getAdd_time()) * 1000))
                        .text(R.id.item_entrust_price, item.getWtprice1())
                        .text(R.id.item_entrust_real_num, item.getCjnum());
                if (item.getOtype() == 2 && item.getType() == 1) {  //市价买入
                    injector.text(R.id.item_entrust_num_text, App.INSTANCE.getString(R.string.strEntrustActivity203))
                            .text(R.id.item_entrust_num, item.getTotalprice());
                } else { //其他
                    injector.text(R.id.item_entrust_num_text, App.INSTANCE.getString(R.string.strEntrustActivity204))
                            .text(R.id.item_entrust_num, item.getWtnum());
                }

                TextView cancel = (TextView) injector.findViewById(R.id.item_entrust_cancel);
                cancel.setTextColor(getResources().getColor(R.color.blue_5d));

                cancel.setVisibility(View.VISIBLE);
                if (item.getCode() == 0) {
                    //0 委托中
                    cancel.setText(App.INSTANCE.getString(R.string.strEntrustActivity208));
                } else if (item.getCode() == 1) {
                    //1 交易中
                    cancel.setText(App.INSTANCE.getString(R.string.strEntrustActivity209));
                } else if (item.getCode() == 2) {
                    //2已成交
                    cancel.setText(App.INSTANCE.getString(R.string.strEntrustActivity206));
                } else if (item.getCode() == -1) {
                    // -1 已撤销
                    cancel.setText(App.INSTANCE.getString(R.string.strEntrustActivity207));
                } else {
                    cancel.setVisibility(View.GONE);
                }
                if (item.getCode() == 0 || item.getCode() == 1) {
                    cancel.setClickable(true);
                    cancel.setOnClickListener(v -> mPresenter.cancelOrder(item.getOrders_id()));
                } else {
                    cancel.setClickable(false);
                }
            }
        });
        slimAdapter = "all".equals(fragmentType) ? item_recycler_entrust : level_item_trade_history;
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                //   startTimer();
            } else {
                userData = null;
            }
            refresh();
        });
    }

    public void pingCangSuccess() {
        userViewModel.update();
        refresh();
    }

    public void cancelOrderSuccess() {
        userViewModel.update();
        refresh();
    }

    /**
     * 刷新
     */
    @Subscribe(code = RxBusCode.LEVEL_TRADE_LIST_STATUS_REFRESH, threadMode = ThreadMode.MAIN)
    public void refresh() {
        if (mPresenter != null && userData != null) {
            mPresenter.getTradeList("all".equals(fragmentType) ? 0 + "" : (((TradeListActivity) getActivity()).tradeStatus == 0 ? null : ((TradeListActivity) getActivity()).tradeStatus + ""));
        } else {
            DisposUtil.close(subscribe);
            showEmpty();
        }
    }

    /**
     * 显示无数据布局
     */
    public void showEmpty() {
        AndroidSchedulers.mainThread().scheduleDirect(() -> {

            if (includeEmpty != null) {
                includeEmpty.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
            if (slimAdapter != null) {
                slimAdapter.updateData(new ArrayList<>());
            }
        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePrice(CoinBean stockCoinBean) {
        if (setTip != null && setTip.isShowing()) {
            if (stockCoinBean.getCode().equals(slimAdapter.getDataItem(curPos).getPname())) {
                TipLevelUtil.changeTradeSet(setTip, stockCoinBean.getPrice());
            }
        }

    }

    private void startTimer() {
        if (userData == null)
            return;
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> refresh());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeTab(MainTabChange mainTabChange) {
        if (mainTabChange.getPos() == 2) {
            if (mPresenter != null && userData != null) {
                startTimer();
            }
        } else {
            DisposUtil.close(subscribe);
        }
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(subscribe);
        super.onDestroy();
    }

    public void updateUI(List<Entrust> data) {
        if (data == null || data.size() == 0) {
            if (recyclerView == null)
                return;
            recyclerView.setVisibility(View.GONE);
            includeEmpty.setVisibility(View.VISIBLE);
        } else {
            if (recyclerView == null)
                return;
            recyclerView.setVisibility(View.VISIBLE);
            includeEmpty.setVisibility(View.GONE);
            slimAdapter.updateData(data);
        }
    }
}
